﻿/******************************************************************************
* File description: CpsUdpClient.cpp
* Function: UDP通信线程
* Current Version: 1.0.0
* Author: 郑佰旺
* Date: 2025-07-1
*  -----
*  Copyright by 博坤生物 .
 *****************************************************************************/

#include "CpsUdpClient.h"

extern int npwhfl;

CpsUdpClient* CpsUdpClient::Instance=0;

CpsUdpClient* CpsUdpClient::getInstance()
{
    if(Instance==0)
        Instance =new CpsUdpClient();
    return Instance;
}

CpsUdpClient::CpsUdpClient(QObject *parent): QUdpSocket(parent)
{
    connect(this, &CpsUdpClient::SignalConnectToHost, this, [&](const QString & address, quint16 port) {
        this->abort();
        this->bind(8081);
        this->connectToHost(QHostAddress(address), port, QIODevice::ReadWrite);
    }, Qt::AutoConnection);

    //执行数据发送过程
    QObject::connect(this, &CpsUdpClient::CpsSignalSendingData, this, [&](const QByteArray c_btaData)
    {
        this->write(c_btaData);

        QString str;
        for(int c :c_btaData)
        {
            if(c>=0)
            {
                str += QString(" %1").arg(c, 2, 16, QChar('0')).toUpper();
            }
            else
            {
                str += QString(" %1").arg(c+256, 2, 16, QChar('0')).toUpper();
            }
        }
        str= str.simplified();
        QStringList list=str.split(" ");
        saveLog("发送",list);

    }, Qt::AutoConnection);

    //收到了UDP服务的数据
    QObject::connect(this, &QIODevice::readyRead, this, [&]() {
        QByteArray arr = this->readAll();
        QString str;
        for(int c :arr)
        {
            if(c>=0)
            {
                str += QString(" %1").arg(c, 2, 16, QChar('0')).toUpper();
            }
            else
            {
                str += QString(" %1").arg(c+256, 2, 16, QChar('0')).toUpper();
            }
        }
        str= str.simplified();
        if(str.length()>10)
        {
            QStringList list=str.split("62 00 00");
            for(int i=1;i<list.length();i++){
                QString info ="62 00 00"+list[i];
                receiveDataProcessing(info.split(" "));
            }
        }
    }, Qt::DirectConnection);
}

//
CpsUdpClient::~CpsUdpClient()
{

}

//跨线程转换
void CpsUdpClient::ClientConnectToHost(const QString & address, quint16 port)
{
    emit SignalConnectToHost(address, port);
}

//跨线程转换
void CpsUdpClient::ClientSendingData(const QByteArray & c_btaData)
{
    emit CpsSignalSendingData(c_btaData);
}


/**
 * @brief UdpClient::receiveDataProcessing 处理接收到的下位机数据
 * @param list 下位机接收数据
 */
void CpsUdpClient::receiveDataProcessing(QStringList list){
    if(list.length()>10)
    {
        saveLog("接收",list);
        if(list[0]=="62" && list[1]=="00" && list[2]=="00" && list[3]=="3D")//接收上传数据
        {
            if(list[6]=="22"){
                QString info="正常";
                StaticProperties::purifyingStatus["5"].setValue(info);

                if(StaticProperties::expStatus!=0||npwhfl==1){
                    if(list.length()>10){
                        double finalData=CommonHelper::Common().SixteenToTen(list[7]+" " +list[8]+" " +list[9]+" "+list[10]).toDouble();
                        QSqlDatabase db = dbHelper::openConnection();
                        QSqlQuery query(db);
                        QString sql=QString("Insert into CPSData Values('%1','%2')").arg(CommonHelper::Common().GetDateTimeStr(),QString::number(finalData));
                        query.exec(sql);
                        QMLSignal::I().emitSendCpsData(finalData);
                        if(StaticProperties::isProductTesting){
                            if(StaticProperties::dataThresholdType=="大于"){
                                if(finalData>StaticProperties::dataThreshold){

                                    StaticProperties::isProductTesting=false;

                                    QSqlDatabase db = dbHelper::openConnection();
                                    QSqlQuery query(db);
                                    QString sql="Update ExperimentInfo set isProductTesting='false'";
                                    query.exec(sql);

                                    ExperimentThread::I().run();
                                }
                            }
                            else if(StaticProperties::dataThresholdType=="小于"){
                                if(finalData<StaticProperties::dataThreshold){

                                    StaticProperties::isProductTesting=false;

                                    QSqlDatabase db = dbHelper::openConnection();
                                    QSqlQuery query(db);
                                    QString sql="Update ExperimentInfo set isProductTesting='false'";
                                    query.exec(sql);

                                    ExperimentThread::I().run();
                                }
                            }
                        }
                    }
                }
            }
            else if(list[6]=="23"){
                double chData=CommonHelper::Common().SixteenToTen(list[7]+" " +list[8]+" " +list[9]+" "+list[10]).toDouble()/1000;
                QMLSignal::I().emitSendRadiationData(4,chData);

                double dbData=CommonHelper::Common().SixteenToTen(list[11]+" " +list[12]+" " +list[13]+" "+list[14]).toDouble()/1000;
                QMLSignal::I().emitSendRadiationData(2,dbData);

                double fbData=CommonHelper::Common().SixteenToTen(list[15]+" " +list[16]+" " +list[17]+" "+list[18]).toDouble()/1000;
                QMLSignal::I().emitSendRadiationData(1,fbData);
            }
        }
    }
}

/**
 * @brief UdpClient::IsOnline 是否在线
 * @return 是否超时
 */
bool CpsUdpClient::IsOnline()
{
    return m_bOnLine;
}

/**
 * @brief UdpClient::onTimeout 指令接受超时
 */
void CpsUdpClient::onTimeout(){
    if(!receiveSuccess){
        QMLSignal::I().emitReceiveMsgOutTime();
    }
}

void CpsUdpClient::saveLog(QString type,QStringList list){
    QString str=list.join(" ");
    if(str.length()>0){
        //接收日志处理
        if(list[6]=="22")  //设备上传数据
        {
            DebugLog::I().customType(QString("%1:\n"+str).arg(type), "CpsDataLog");
        }
        else
        {
            DebugLog::I().customType(QString("%1:\n"+str).arg(type), "RadiationDataLog");
        }
    }
}

